﻿namespace Rally_MvvmC.Library
{
    using System;
    using System.Text.RegularExpressions;

    public static class ViewControllerBaseExtension
    {
        public static type PullSession<type>(this ViewControllerBase viewControllerBase, string key)
            where type : class
        {
            return viewControllerBase.TempData[key] as type;
        }

        public static type PeekTemp<type>(this ViewControllerBase viewControllerBase, string key)
            where type : class
        {
            var returnVal = viewControllerBase.TempData[key] as type;
            viewControllerBase.TempData[key] = returnVal;
            return returnVal as type;
        }

        public static type PullTemp<type>(this ViewControllerBase viewControllerBase, string key)
            where type : class
        {
            var returnVal = viewControllerBase.TempData[key] as type;
            return returnVal as type;
        }

        public static type PeekTempVal<type>(this ViewControllerBase viewControllerBase, string key)
            where type : struct
        {
            var returnVal = viewControllerBase.TempData[key];
            if (returnVal == null)
            {
                returnVal = 0;
            }

            viewControllerBase.TempData[key] = returnVal;
            return (type)returnVal;
        }

        public static void PushTemp(this ViewControllerBase viewControllerBase, string key, object value)
        {
            viewControllerBase.TempData[key] = value;
        }

        public static type PeekPushTemp<type>(this ViewControllerBase viewControllerBase, string key, Func<type> pushFunction)
        where type : class
        {
            var returnVal = viewControllerBase.TempData[key] as type;
            if (returnVal == null)
            {
                returnVal = pushFunction.Invoke();
            }

            viewControllerBase.TempData[key] = returnVal;
            return returnVal as type;
        }

        public static type PeekPushTempVal<type>(this ViewControllerBase viewControllerBase, string key, Func<type> pushFunction)
        where type : struct
        {
            var returnVal = viewControllerBase.TempData[key];
            if (returnVal == null || (returnVal is int && (int)returnVal == 0))
            {
                returnVal = pushFunction.Invoke();
            }

            viewControllerBase.TempData[key] = returnVal;
            return (type)returnVal;
        }
    }
}
